<?php
namespace Fox\Core;

use Fox;

/**
 * Fox\Core\View
 * 视图类
 * 
 * @author keluo <keluo@focrs.com>
 * @copyright 2017 Focrs, Co.,Ltd
 * @package Fox
 * @since 2017-10-1
 */
class View {
     
    private $_variables = [];
    
    public function __construct() {}
    
    public function __set($variable, $value) {
        $this->_variables[$variable] = $value;
    }
    
    public function __get($variable) {
        return isset($this->_variables[$variable]) ? $this->_variables[$variable] : null;
    }
    
    /**
     * 输出html
     * @param array $variables 
     * @param string $view
     * @param boolean $render 是否立即渲染
     * @throws Exception
     */
    public function Html($variables = [], $view = '', $render = true) {
        $this->_variables = $variables;
        if($view == '') {
            $viewPath = Fox::Instance()->app.'/rav/'.(Fox::Request()->route ? : 'index').'/view.php';
        } elseif(strpos($view, '/')) {
            $viewPath = Fox::Instance()->app.'/rav/'.$view.'.php';
        } else {
            $viewPath = Fox::Instance()->app.'/rav/'.Fox::Request()->control.'/'.$view.'.php';
        }
        
        if(file_exists($viewPath) && is_file($viewPath)) {
            ob_start('ob_gzhandler') || ob_start();
            require $viewPath;
            $data = ob_get_clean();
            if($render) {
                $data = gzencode($data, 9);
                header("Content-Encoding: gzip");
                header("Vary: Accept-Encoding");
                header("Content-Length: ".strlen($data));
                echo $data;
            } else return $data;
        } else {
            throw new \Exception('View file does not exist: '.$viewPath);
        }
    }
    
    /**
     * 加载视图小组件
     * @param string $view
     * @param array $variables 传递给组件的变量
     * @throws Exception
     */
    public function Widget($view, $variables = []) {
        extract($variables);
        $path = Fox::Instance()->app.'/rav/-widget/'.$view.'.php';
        
        if(file_exists($path) && is_file($path)) {
            require $path;
        } else {
            throw new \Exception('Widget file doest not exist: '.$path);
        }
    }
    
    /**
     * 输出json格式数据
     * @param boolean $status 结果状态
     * @param mixed $data 返回数据
     */
    public function Json($status, $data = '') {
        header('Content-type: application/json; charset=utf-8');
        die(json_encode([
            'status' => $status ? 1 : 0, // 成功状态码
            'data' => $data, // 数据
        ]));
    }
    
}